package com.situ.stmall.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.stmall.entity.User;
import com.situ.stmall.mapper.UserMapper;
import com.situ.stmall.service.UserService;
import com.situ.stmall.util.MD5Util;

/**
 * 1. 创建Service层的接口
 * 2. 声明方法
 * 3. 创建Service层的实现类, 添加@Service注解
 * 4. 实现Service层的方法, 使用Autowired注入Mapper层的对象
 * 
 * @author bobzyh
 *
 */
@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public int reg(User user, String repassword) {
		// 1. 验证输入格式
		if (user.getUsername().length() < 3 || user.getUsername().length() > 16) {
			return -1;
		}
		if (user.getPassword().length() < 3 || user.getPassword().length() > 16) {
			return -2;
		}
		
		// 2. 比较两次密码是否一致
		if (  !  user.getPassword().equals(repassword)) {
			return -3;
		}
		
		// 3. 判断账号是否可用
		User selectUser = userMapper.selectByUsername(user.getUsername());
		if (selectUser != null) {
			return -4;
		}
		
		// 4. 写入数据库
		user.setPassword(MD5Util.getMD5(repassword));
		return userMapper.insert(user);
	}

	@Override
	public User login(User user) throws Exception {
		// 1. 验证格式
		if (user.getUsername().length() < 3 || user.getUsername().length() > 16) {
			throw new Exception("账号格式不对");
		}
		if (user.getPassword().length() < 3 || user.getPassword().length() > 16) {
			throw new Exception("密码格式不对");
		}
		
		// 2. 查询账号
		User selectUser = userMapper.selectByUsername(user.getUsername());
		if (selectUser == null) {
			throw new Exception("账号不存在");
		}
		
		// 3. 验证密码
		if ( ! selectUser.getPassword().equals(MD5Util.getMD5(user.getPassword()))) {
			throw new Exception("密码不正确");
		}
		
		// 4. 验证用户状态
		if (selectUser.getStatus() == 1) {
			throw new Exception("账号已被禁用, 请联系管理员");
		}
		
		return selectUser;
	}

}



